<template>
	<view class="userInfo">
	   <u-cell-group>
	        <u-cell  title="头像" isLink>
				<button class="chooseAvatarBtn" slot="value" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
					<image :src="userInfo.avatar"  class="avatar" />
				</button>
			</u-cell>
			<u-cell isLink title="昵称" >
				<!-- confirm-type可以改手机上的文字 -->
				<input confirm-type="send" type="nickname" @blur="updateNickName" :value="userInfo.nickName" placeholder="请输入昵称" class="nickName" slot="value" />
			</u-cell>
		</u-cell-group>
		<life-button @click="goBack"  bg-color="#fff" iscolor="#333" icon="../../static/icon/confirm.png">确认</life-button>
	</view>
	
</template>

<script>
	import {updateUserInfo} from '@/api/user.js'
	export default {
		data() {
			return {
				
			}
		},
		computed:{
			userInfo(){
				return this.$store.state.user.userInfo
			}
		},
		methods: {
			onChooseavatar(e){
				// console.log(e)
				// console.log(e.detail.avatarUrl) //这是拿到的图片
				// uni.showToast({
				// 	title:e.detail.avatarUrl
				// })
				const avatar = e.detail.avatarUrl
				uni.uploadFile({
					url:"https://live-api.itheima.net/upload",
					filePath:avatar,
					name:"file",
					header: {
						Authorization:'Bearer ' + this.$store.state.user.userToken.token
					},
					formData:{
						type:'avatar'
					},
					success:async (res) =>{
						// console.log(res)
						const data = JSON.parse(res.data)
						if(data.code !== 10000){
							return uni.showToast({
								icon:'error',
								title:'上传失败'
							})
						}
						
						console.log(JSON.parse(res.data))
						// 要刷新页面，就把vuex调用方法
						await this.$store.dispatch('user/loadUserInfo')
						// 提示
						uni.showToast({
							icon:'success',
							title:'上传成功'
						})
					}
				})
			},
			// 失去焦点
			async updateNickName(e){
				// console.log(e)
				const value = e.detail.value
				try{
					// 请求到接口
					await updateUserInfo({nickName:e.detail.value})
					// console.log(res)
					// 再更新页面，更新vuex，调用vuex的方法
					await this.$store.dispatch('user/loadUserInfo')
					// 给提示
					uni.showToast({
						icon:'success',
						title:'更新昵称'
					})
				}catch(e){
					//TODO handle the exception
				}
			},
			goBack(){
				uni.navigateBack({
					detal:'1'
				})
			}
			
		}
	}
</script>

<style lang="scss" scoped>
.userInfo {
  height: 100%;
  background-color: #FAFAFA;

// 是内部的组件那要用穿透选择器
  ::v-deep .u-cell__body {
    height: 102rpx;
    padding: 0 30rpx;
    background-color: #fff;

    .u-cell__title-text {
      color: #333 !important;
      font-size: 28rpx !important;
    }
  }

  .avatar {
    width: 42rpx;
    height: 42rpx;
	border-radius: 50%;
  }

  .nickName {
    text-align: right;
  }
  .chooseAvatarBtn::after,
  .chooseAvatarBtn {
    background-color: unset;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
